"""""""""""""""""""""""""
" File: _vimrc
" Version: 2011-04-27 19:14:35 
" By: bucunzai <freecityer@gmail.com>
"""""""""""""""""""""""""

"""""""""""""""""""""""""
" General Setting
"""""""""""""""""""""""""
" Don't be compatible with vi
set nocompatible

" Load plugins by pathogen.vim
filetype off
call pathogen#runtime_append_all_bundles()
call pathogen#helptags()

" Enable filetype plugin 
if has("eval")
    filetype on
    filetype plugin on
    filetype indent on
endif

" Set auto read when a file is changed from the outside
set autoread
set autochdir

" Show us the command we're typing / cmd with slash
set showcmd
set shellslash

set clipboard+=unnamed " share windows clipboard

"mouse enabled all the time
set mouse=a

"Better include path
set path+=src/

" <leader> to ,
let mapleader=","
let maplocalleader=","

" Default keyword
if has("unix")
    "set keywordprg=:help
endif
" help language = cn!
set helplang=en 
" Fixed menu language
if has("win32")
    source $VIMRUNTIME/delmenu.vim
    set langmenu=en_US
    source $VIMRUNTIME/menu.vim
    language messages zh_CN.utf-8
endif

"Persistent Undo
set undofile
set undodir=~/.vim/tmp

"""""""""""""""""""""""""
" Colors and Fonts
"""""""""""""""""""""""""
"Enable syntax highlighting
if has("syntax")
    syntax on
endif

"Set fonts and colorscheme
if has("win32")
    "set gfn=YaHei_Consolas_Hybrid:h11:cANSI 
    set guifont=Dejavu_Sans_Mono:h11:cANSI
    set gfw=Microsoft_YaHei:h11
    colorscheme wombat256
endif

if has("unix")
    set t_Co=256
    set background=dark
    colorscheme wombat256mod
endif

"Highlight current line/column
"if has("gui_running")
    set cursorline
    hi cursorline guibg=#333333
    "set cursorcolumn
    "hi CursorColumn guibg=#333333
"endif

"""""""""""""""""""""""""
" VIM UserInterface 
"""""""""""""""""""""""""
"Set lines to the curors - when moving vertical... scrolloff sidescrolloff
set so=3
set sidescrolloff=2

"Turn on Wild Menu
set wildmode=longest,list,full

"Always show current position
set ru

"The commander bar is 2 high
set cmdheight=2

"Show line number
set nu

"Do not redraw, when running macros..lazyredrw, sometimes didn't works
"set lz

"Change buffer - without saving
set hid

"Set backspace delete lots of things
set backspace=indent,eol,start " backspace=delete

"Backspace and cursor keys wrap to
set whichwrap+=<,>,h,l,[,]

"Set magic on, for regular expression
set magic

"Search options: ignore case when searching, incremental search, highlight search
set ignorecase
set smartcase
set incsearch
set hlsearch

"No sound on errors.
set noerrorbells
set novisualbell
set vb t_vb=

"How many tenths of a second to blink
set mat=2

"Statusbar
set laststatus=2
set statusline=[%{strftime(\"%c\",getftime(expand(\"%:p\")))}]
set statusline+=[%{&fileformat},
set statusline+=%Y,%k%{(&fenc==\"\")?&encoding:&fenc}%{(&bomb?\",BOM\":\"\")}]
set statusline+=%= "right align
set statusline+=%o,0x%-8B\  " current char
set statusline+=%-14.\((%l,%c%V\)%)\ %<%P        " offset

" Folding 
set nofen
set fdl=0
set foldenable
set fdm=syntax

"""""""""""""""""""""""""
" GUI Settings
"""""""""""""""""""""""""
"Tab configuration
map <leader>tn :tabnew %<cr>
map <leader>te :tabedit
map <leader>tc :tabclose<cr>
map <leader>tm :tabmove
try
    set switchbuf=usetab
    set stal=2
catch
endtry

if has("gui_running")
    set guioptions=mcrt

    if has("win32")
        set lines=30
        set columns=110
        " set window position
        winpos 165 125 
        "map <F8> <ESC>:set gfn=YaHei_Consolas_Hybrid:h12:cANSI<CR>
    endif

    if has("unix")
        set lines=30
        set columns=110
        " set window position
        winpos 255 180 
        set gfn=Dejavu\ Sans\ Mono\ 11
    endif

endif
"""""""""""""""""""""""""
" Text options
"""""""""""""""""""""""""
set expandtab
set shiftwidth=4
set softtabstop=4
set tabstop=4
    """""""""""""""""""""
    " Indent
    """""""""""""""""""""
    " Wrap lines
    set wrap
    " C-style indenting
    set cindent
    " set autoindent smartindent
    set ai
    set si

"Super paste
"map <F6> :set paste!<BAr>set paste?<CR>
map <F6> :set paste<CR>
map <S-F6> :set nopaste<CR>

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Set Completion
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set completeopt=longest,menu
autocmd FileType python set omnifunc=pythoncomplete#Complete
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd FileType html,htm set omnifunc=htmlcomplete#CompleteTags
autocmd FileType css set omnifunc=csscomplete#CompleteCSS
autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
autocmd FileType c set omnifunc=ccomplete#Complete

"""""""""""""""""""""""""
" Plugin configuration
"""""""""""""""""""""""""
" BufExplorer
let g:bufExplorerDefaultHelp=0
let g:bufExplorerMaxHeight=25
let g:bufExplorerResize=1
let g:bufExplorerShowRelativePath=1
let g:bufExplorerSortBy='mru'
let g:bufExplorerSplitBelow=1
let g:bufExplorerSplitRight=0 
let g:bufExplorerSplitVertSize=20 
let g:bufExplorerSplitVertical=1 
let g:bufExplorerUseCurrentWindow=1 

" Taglist
set tags+=tags;
if has("win32")
    set path+=.
    let Tlist_Ctags_Cmd='ctags.exe' "Location of ctags
    " pydiction
    let g:pydiction_location = '$VIM/vimfiles/pydiction/complete-dict'
endif
let Tlist_Use_Right_Window=1
let Tlist_Auto_Open=0
let Tlist_Enable_Fold_Column=0
let Tlist_Compact_Format=1
let Tlist_WinWidth=32
let Tlist_Exit_OnlyWindow=1
let Tlist_File_Fold_Auto_Close=1
let Tlist_Process_File_Always=0
let Tlist_Highlight_Tag_On_BufEnter=1
let Tlist_GainFocus_On_ToggleOpen=1
"let Tlist_Close_On_Select=1
nnoremap <silent> <F2> <ESC>:TlistToggle<CR>
nnoremap <silent> <S-F2> <ESC>:TlistUpdate<CR>

" SuperTab.vim
""let SuperTabMappingForward='<c-tab>'
""let SuperTabMappingBackward='<s-tab>'
"let g:SuperTabDefaultCompletionType="<C-X><C-U>"
"let g:SuperTabRetainCompletionType=2

" matchit.vim
let b:match_ignorecase=1

"Setting for :TOhtml
let html_number_lines=1
let html_use_css=1
let use_xhtml=1

" txtbrowser.vim
" au BufRead,BufNewFile *.txt setlocal ft=txt
 
" vimperator
au BufNewFile,BufRead *vimperatorrc*,*.vimp set filetype=vimperator

" html.vim
let g:no_html_toolbar = 1
let g:do_xhtml_mappings = 'yes'
let g:html_tag_case = 'lowercase'

" acp.vim & SnipMate.vim
"let g:acp_behaviorSnipmateLength =2
"let g:acp_enableAtStartup = 0
"let g:acp_completeOption = '.,w,b,u,t,i,k'
autocmd FileType python set ft=python.django " For SnipMate
autocmd FileType html set ft=html.django_template.jquery " For SnipMate & jquery

" XPTemplate.vim
"let g:SuperTabMappingForward = '<Plug>supertabKey'
"let g:xptemplate_fallback = '<Plug>supertabKey'
"let g:xptemplate_key = 's-<TAB>'
let g:xptemplate_nav_next = '<C-j>'
let g:xptemplate_nav_prev = '<C-k>'
"let g:xptemplate_nav_cancel = '<C-c>'
"let g:xptemplate_brace_complete = 1

" NeoComplCache.vim
"if has("win32")
    " Use neocomplcache. 
    let g:neocomplcache_enable_at_startup = 1 
    " Use smartcase. 
    let g:neocomplcache_enable_smart_case = 1 
    " Use camel case completion. 
    let g:neocomplcache_enable_camel_case_completion = 1 
    " Use underbar completion. 
    let g:neocomplcache_enable_underbar_completion = 1 
    " Set minimum syntax keyword length. 
    let g:neocomplcache_min_syntax_length = 3 
    " disable auto complete
    "let g:neocomplcache_disable_auto_complete = 1

    " Plugin key-mappings. 
    imap <C-o>     <Plug>(neocomplcache_snippets_expand) 
    smap <C-o>     <Plug>(neocomplcache_snippets_expand) 
    inoremap <expr><C-g>     neocomplcache#undo_completion() 
    inoremap <expr><C-l>     neocomplcache#complete_common_string()
    " Recommended key-mappings. 
    " <CR>: close popup and save indent. 
    inoremap <expr><CR>  neocomplcache#smart_close_popup() ."\<CR>"
    " <TAB>: completion. 
    "inoremap <expr><TAB>  pumvisible() ? "\<C-n>" : "\<TAB>" 
    "inoremap <expr><c-i>  pumvisible() ? "\<C-n>" : "\<TAB>" 
    " <C-h>, <BS>: close popup and delete backword char. 
    inoremap <expr><C-h> neocomplcache#smart_close_popup()."\<C-h>" 
    inoremap <expr><BS> neocomplcache#close_popup()."\<C-h>" 
    inoremap <expr><C-c>  neocomplcache#close_popup() 
    "inoremap <expr><C-e>  neocomplcache#cancel_popup()
"endif

" c-support.vim and bash-support.vim
"let g:C_GlobalTemplateFile = '~/.vim/c-support/templates/Templates'
"let g:C_TemplateOverwrittenMsg = 'no'
"let g:BASH_GlobalTemplateFile = '~/.vim/bash-support/templates/Templates'
"let g:BASH_TemplateOverwrittenMsg = 'no'

" zencoding.vim
" php extends with html&css, html extends with css
let g:user_zen_settings = {
            \ 'php' :{
            \ 'extends' : 'html',
            \ 'filters' : 'html,c',
            \ },
            \ 'html' :{
            \ 'filters' : 'html',
            \ },
            \ 'css' :{
            \ 'filters' : 'fc',
            \ },
            \}
" using ctrl-e expand key
let g:user_zen_expandabbr_key = '<c-e>'
let g:user_zen_complete_tag = 1
"let g:user_zen_leader_key = '<c-e>'

"""""""""""""""""""""""""
" Command-line config
"""""""""""""""""""""""""
func! Cwd()
    let cwd = getcwd()
    return "e " . cwd 
endfunc

func! DeleteTillSlash()
    let g:cmd = getcmdline()
    if MySys() == "linux" || MySys() == "mac"
        let g:cmd_edited = substitute(g:cmd, "\\(.*\[/\]\\).*", "\\1", "")
    else
        let g:cmd_edited = substitute(g:cmd, "\\(.*\[\\\\]\\).*", "\\1", "")
    endif
    if g:cmd == g:cmd_edited
        if MySys() == "linux" || MySys() == "mac"
            let g:cmd_edited = substitute(g:cmd, "\\(.*\[/\]\\).*/", "\\1", "")
        else
            let g:cmd_edited = substitute(g:cmd, "\\(.*\[\\\\\]\\).*\[\\\\\]", "\\1", "")
        endif
    endif
    return g:cmd_edited
endfunc

func! CurrentFileDir(cmd)
    return a:cmd . " " . expand("%:p:h") . "/"
endfunc

"Smart mappings on the command line
cno $h e ~/
cno $d e ~/Desktop/
cno $j e ./

cno $q <C-\>eDeleteTillSlash()<cr>

cno $c e <C-\>eCurrentFileDir("e")<cr>

cno $tc <C-\>eCurrentFileDir("tabnew")<cr>
cno $th tabnew ~/
cno $td tabnew ~/Desktop/

"Bash like
cnoremap <C-A>  <Home>
cnoremap <C-E>  <End>
cnoremap <C-B>  <Left>
cnoremap <C-F>  <Right>
cnoremap <C-K>  <C-U>
"cnoremap <C-P>  <Up>
"cnoremap <C-N>  <Down>
"imap <C-A>  <Home>
"imap <C-E>  <End>
imap <C-B>  <Left>
imap <C-F>  <Right>

"""""""""""""""""""""""""
" Buffer realted
"""""""""""""""""""""""""
"Fast open a buffer by search for a name
"map <c-q> :sb
"Open a dummy buffer for paste
map <leader>q :e ~/buffer<cr>

"""""""""""""""""""""""""
" Encoding
"""""""""""""""""""""""""
" Favorite filetypes
set fileformats=unix,dos,mac

" multi-encoding setting
if has("multi_byte")
    "set bomb 
    set encoding=utf-8
    set fileencodings=ucs-bom,utf-8,cp936,gb18030,big5,euc-jp,sjis,euc-kr,ucs-2le,latin-1 
    set fencs=utf-8,gbk,chinese,latin1
    set nobomb
    " CJK environment detection and corresponding setting 
    if v:lang =~ "^zh_CN" 
        " Use cp936 to support GBK, euc-cn == gb2312 
        set encoding=utf-8
        set termencoding=utf-8
        set fileencoding=utf-8 
    elseif v:lang =~ "^zh_TW" 
        " cp950, big5 or euc-tw 
        " Are they equal to each other? 
        set encoding=big5 
        set termencoding=big5 
        set fileencoding=big5 
    elseif v:lang =~ "^ko" 
        " Copied from someone's dotfile, untested 
        set encoding=euc-kr 
        set termencoding=euc-kr 
        set fileencoding=euc-kr 
    elseif v:lang =~ "^ja_JP" 
        " Copied from someone's dotfile, untested 
        set encoding=euc-jp 
        set termencoding=euc-jp 
        set fileencoding=euc-jp 
    endif 
    " Detect UTF-8 locale, and replace CJK setting if needed 
    if v:lang =~ "utf8$" || v:lang =~ "UTF-8$" 
        set encoding=utf-8 
        set termencoding=utf-8 
        set fileencoding=utf-8 
    endif 
else 
    echoerr "Sorry, this version of (g)vim was not compiled with multi_byte" 
endif

"""""""""""""""""""""""""
" Filetype generic
"""""""""""""""""""""""""
" HTML related
" PHP & Ruby section
autocmd FileType ruby map <buffer> <leader><space> :w!<cr>:!ruby %<cr>
autocmd FileType php compiler php
autocmd FileType php map <buffer> <leader><space> <leader>cd:w<cr>:make %<cr>
" Vim section
autocmd FileType vim set nofen

"""""""""""""""""
"Key Mappings
"""""""""""""""""
"map space as pagedown
noremap <Space> <PageDown>
noremap <S-Space> <PageUp>
"map Silent to disable "Press Enter or type command to continue" prompt
command! -nargs=1 Silent
\ | execute 'silent !'.<q-args>
\ | execute 'redraw!'
if has("unix")
    map <F3> <ESC>:!python %<CR>
    " open current file via local web server
    map <F9> <ESC>:Silent w3m %<CR>
    map <F10> <ESC>:Silent opera http://localhost/%:t<CR>
    map <F12> <ESC>:Silent firefox http://localhost/%:t<CR>
    if has("gui_running")
    map <F10> <ESC>:silent !opera http://localhost/%:t<CR>
    map <F12> <ESC>:silent !firefox http://localhost/%:t<CR>
    endif
endif
if has("win32")
    inoremap <C-v> <esc>:set paste<cr>mui<C-R>+<esc>mv'uV'v=:set nopaste<cr>
    map <F3> <ESC>:!python %<CR>
    "vnoremap <F6> "+y
    " open current file via local web server
    map <F12> <ESC>:silent ! start http://localhost/%:t<CR>
endif

"ctrl-L refresh the screen, clean highlight by search
nnoremap <Plug>old_c_l <C-l>
nmap <silent><C-l> :nohlsearch<CR><Plug>old_c_l

map <F7> :set spell<CR>
map <S-F7> :set nospell<CR>
if has("win32")
    "use ctrl-s saving, also in Insert mode
    noremap <C-S> :update<CR>
    vnoremap <C-S> <C-C>:update<CR>
    inoremap <C-S> <C-O>:update<CR>
    nnoremap <C-Z> u
    set dictionary+=$VIMRUNTIME/dict/dicts.txt
    "set dictionary+=$VIMRUNTIME/dict/words
    "faster way to edit the vimrc file
    map <silent> <leader>ee :e $vim/_vimrc<cr>
    map <silent> <leader>sv :source $vim/_vimrc<cr>
    map <silent> <leader>hs :e c:/WINDOWS/SYSTEM32/drivers/etc/hosts<cr>
endif
if has("unix")
    map <silent> <leader>ee :e ~/.vimrc<cr>
    map <silent> <leader>sv :source ~/.vimrc<cr>
    map <silent> <leader>hs :e /etc/hosts<cr>
endif

"""""""""""""""""
" personal info
"""""""""""""""""
" source personal.vimrc
if has("win32")
    so $VIM/personal.vimrc
    "set relativenumber
endif
